﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.SessionState;
using System.Configuration;

namespace RedisSessionStore.NoLock
{
	public class RedisNoLockSessionStateStoreProvider : SessionStateStoreProviderBase
	{
		protected readonly static Int32 _defaultTimeout = 30; //TODO: Get timeout from setting
		protected String _redisServer;
		protected Int32 _redisDb = 1; //TODO: Get from config

		public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
		{
			_redisServer = config["redisServer"];
			if (String.IsNullOrEmpty(_redisServer))
				throw new ConfigurationException("You have to specify 'redisServer' in session config");

			base.Initialize(name, config);
		}

		public override SessionStateStoreData CreateNewStoreData(System.Web.HttpContext context, int timeout)
		{
			string sessionId = context.Request.Cookies[RedisNoLockSessionIDManager.CookieName].Value;
			return new SessionStateStoreData(new RedisNoLockSessionStateItemsCollection(sessionId, _defaultTimeout, _redisServer, _redisDb), SessionStateUtility.GetSessionStaticObjects(context), timeout);
		}

		public override void InitializeRequest(System.Web.HttpContext context) { }
		public override void CreateUninitializedItem(System.Web.HttpContext context, string id, int timeout) { }
		public override void Dispose() { }
		public override void EndRequest(System.Web.HttpContext context) { }
		public override SessionStateStoreData GetItem(System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
		{
			//TODO: Check parameters
			lockAge = TimeSpan.Zero;
			lockId = null;
			locked = false;
			actions = SessionStateActions.None;
			return new SessionStateStoreData(new RedisNoLockSessionStateItemsCollection(id, _defaultTimeout, _redisServer, _redisDb), SessionStateUtility.GetSessionStaticObjects(context), _defaultTimeout);
		}

		public override SessionStateStoreData GetItemExclusive(System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
		{
			return this.GetItem(context, id, out locked, out lockAge, out lockId, out actions);
		}

		public override void ReleaseItemExclusive(System.Web.HttpContext context, string id, object lockId) { }
		public override void RemoveItem(System.Web.HttpContext context, string id, object lockId, SessionStateStoreData item) { }
		public override void ResetItemTimeout(System.Web.HttpContext context, string id) { }
		public override void SetAndReleaseItemExclusive(System.Web.HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { }
		public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
		{
			return false;
		}
	}
}
